from channels.generic.websocket import WebsocketConsumer
from kubernetes.stream import stream
from threading import Thread
from kubernetes import client
from libs import k8s

# 多线程
class K8sStreamThread(Thread):
    def __init__(self, websocket, container_stream):
        Thread.__init__(self)
        self.websocket = websocket
        self.stream = container_stream
    def run(self):
        try:
            for line in self.stream:
                # 读取流的输出，发送到websocket客户端
                self.websocket.send(line.decode())
        except Exception as e:
            print(e)

# 继承WebsocketConsumer 类，并修改下面几个方法，主要连接到容器
class StreamLogConsumer(WebsocketConsumer):
    def connect(self):
        # self.scope 请求头信息
        self.namespace = self.scope["url_route"]["kwargs"]["namespace"]
        self.pod_name = self.scope["url_route"]["kwargs"]["pod_name"]
        self.container = self.scope["url_route"]["kwargs"]["container"]

        # 获取登录的认证信息
        k8s.load_auth_config()
        core_api = client.CoreV1Api()

        try:
            # 连接pod日志接口
            self.conn_stream = core_api.read_namespaced_pod_log(
                                 name=self.pod_name,
                                 namespace=self.namespace,
                                 container=self.container,
                                 follow = True,
                                 _preload_content=False).stream()
            # 通过多线程打开连接pod日志接口
            kube_stream = K8sStreamThread(self, self.conn_stream)
            kube_stream.start()
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "你没有进入容器终端权限！"
            else:
                msg = "连接容器错误，可能是传递的参数有问题！"

        self.accept()